/* 参考 https://github.com/mhurwi/meteor-with-express-example */
import express from 'express';
const app = express();
const Widgets = new Mongo.Collection('widgets');
const Router = express.Router();

Router.get('/widgets/:id',function(req,res,next){
    const widget = Widgets.findOne(req.params.id);
    res.status(200).json({ data: widget });
})

Router.get('/widgets/:id',function(req,res,next){
    updateWidget(req,res)
})

Router.get('/widgets/:id',function(req,res,next){
    const result =  Widgets.remove(req.params.id);
    res.status(202).json({ data: result });
})

Router.get('/widgets',function(req,res,next){
    const widgets = Widgets.find().fetch();
    res.status(200).json({ data: widgets });
})

Router.get('/insert-widgets',function(req,res,next){
    console.log(req.body)
    console.log(req.params)
    createWidget(req,res)
})

async function getWidget(req, res) {
  const widget = await Widgets.findOne(req.params.id);
  res.status(200).json({ data: widget });
}

async function updateWidget(req, res) {
  const result = await Widgets.update(req.params.id, { $set: { name: req.body.name, color: req.body.color } });
  const widget = await Widgets.findOne(req.params.id);

  res.status(200).json({ data: widget });
}

async function createWidget(req, res) {
  const widgetId = await Widgets.insert({
    name: req.body.name,
    color: req.body.color
  });
  const widget = await Widgets.findOne(widgetId);

  res.status(201).json({ data: widget });
}

async function deleteWidget(req, res) {
  const result = await Widgets.remove(req.params.id);

  res.status(202).json({ data: result });
}



export default Router;
